<template>
	<div class="gk-layout-container">
		<div class="gk-layout-header">
			<!--工具栏-->
			<div class="toolbar" style="float:left;">
				<el-form :inline="true" :model="filters" :size="global.gSize">
					<el-form-item>
						<el-input v-model="filters.name" :placeholder="$t('role.name')"></el-input>
					</el-form-item>
					<el-form-item>
						<kt-button icon="fa fa-search" :label="$t('action.search')" perms="sys:role:view" type="primary"
							@click="findPage(null)" />
					</el-form-item>
					<el-form-item>
						<kt-button icon="fa fa-plus" :label="$t('action.add')" perms="sys:role:add" type="primary"
							@click="handleAdd" />
					</el-form-item>
				</el-form>
			</div>
		</div>
		<!--表格内容栏-->
		<div class="gk-layout-main">
			<my-table :data="pageResult.content" >
				<el-table-column :label="$t('action.desc')" width="50"  fixed="left" header-align="center" align="center">
					<template slot-scope="scope"> {{scope.$index+1}} </template>
				</el-table-column>
				<column   prop="name" :label="$t('role.name')" />
				<column  prop="remark" :label="$t('role.remark')"/>
				<column  prop="createBy" :label="$t('public.createName')"/>
				<column prop="createTime" :label="$t('public.createTime')"/>
				<el-table-column header-align="center" align="center" width='400' :label="$t('action.operation')">
					<template slot-scope="scope">
						<kt-delete-button   perms="sys:role:delete"  @click="handleDelete(scope.$index, scope.row)" />
						<kt-button icon="fa fa-edit" :label="$t('action.edit')" perms="sys:role:edit" :size="global.gSize"
							@click="handleEdit(scope.$index, scope.row)" />
						<kt-button icon="fa fa-edit" label="权限" perms="sys:role:edit" :size="global.gSize"
							@click="handleRoleSelectChange(scope.$index, scope.row)" />
					</template>
				</el-table-column>
			</my-table>
		</div>
		<!--分页栏-->
		<div class="gk-layout-footer">
			<el-pagination layout="total, prev, pager, next, jumper" @current-change="findPage"
				:current-page="pageRequest.pageNum" :page-size="pageRequest.pageSize" :total="pageResult.totalSize">
			</el-pagination>
		</div>
		<!-- </el-col> -->
		<!--新增编辑界面-->
		<el-dialog :title="operation?$t('action.add'):$t('action.edit')" width="40%" :visible.sync="dialogVisible"
			:close-on-click-modal="false">
			<el-form :model="dataForm" label-width="80px" :rules="dataFormRules" ref="dataForm" :size="global.gSize">
				<el-form-item label="ID" prop="id" v-if="false">
					<el-input v-model="dataForm.id" :disabled="true" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item :label="$t('role.name')" prop="name">
					<el-input v-model="dataForm.name" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item :label="$t('role.remark')" prop="remark">
					<el-input v-model="dataForm.remark" auto-complete="off" type="textarea"></el-input>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button :size="global.gSize" @click.native="dialogVisible = false">{{$t('action.cancel')}}</el-button>
				<el-button :size="global.gSize" type="primary" @click.native="submitForm" :loading="editLoading">
					{{$t('action.submit')}}</el-button>
			</div>
		</el-dialog>
		<el-dialog :visible.sync="dialogRoleVisible" width="70%">
			<!--角色菜单，表格树内容栏-->
			<div class="menu-container" :v-if="true">
				<div class="menu-header">
					<span><B>{{$t('role.rolePermission')}}</B></span>
				</div>
				<el-tree :data="menuData" :size="global.gSize" show-checkbox node-key="id" :props="defaultProps"
					style="width: 100%;pading-top:20px;" ref="menuTree" :render-content="renderContent"
					v-loading="menuLoading" :element-loading-text="$t('action.loading')" :check-strictly="true"
					@check-change="handleMenuCheckChange">
				</el-tree>
				<div style="float:left;padding-left:24px;padding-top:12px;padding-bottom:4px;">
					<el-checkbox v-model="checkAll" @change="handleCheckAll" :disabled="this.selectRole.id == null">
						<b>{{$t('action.selectALL')}}</b></el-checkbox>
				</div>
				<div slot="footer" class="dialog-footer">
					<el-button :size="global.gSize" @click.native="dialogRoleVisible = false">{{$t('action.cancel')}}
					</el-button>
					<kt-button :label="$t('action.reset')" perms="sys:role:edit" type="primary" @click="resetSelection"
						:disabled="this.selectRole.id == null" />
					<kt-button :label="$t('action.submit')" perms="sys:role:edit" type="primary" @click="submitAuthForm"
						:disabled="this.selectRole.id == null" :loading="authLoading" />
				</div>
			</div>
		</el-dialog>
	</div>
</template>

<script>

	import KtButton from "@/views/Core/KtButton"
	import KtDeleteButton from "@/views/Core/KtDeleteButton"
	import TableTreeColumn from '@/views/Core/TableTreeColumn'
	import MyTable from "@/views/Core/MyTable"
     import Column from "@/views/Core/Column"
	import { format } from "@/utils/datetime"
	export default {
		components: {
MyTable,
Column,
			KtButton,
			KtDeleteButton,
			TableTreeColumn
		},
		data() {
			return {
				
				filters: {
					name: ''
				},
				columns: [



				],
				pageRequest: { pageNum: 1, pageSize:20 },
				pageResult: {},

				operation: false, // true:新增, false:编辑
				dialogVisible: false, // 新增编辑界面是否显示
				dialogRoleVisible: false,
				editLoading: false,
				// 新增编辑界面数据
				dataForm: {
					id: 0,
					name: '',
					remark: ''
				},
				selectRole: {},
				menuData: [],
				menuSelections: [],
				menuLoading: false,
				authLoading: false,
				checkAll: false,
				currentRoleMenus: [],
				defaultProps: {
					children: 'children',
					label: 'name'
				}
			}
		},
		computed: {
			dataFormRules() {
				const dataFormRules = {
					name: [{ required: true, message: this.getKey("role.roleNameInput"), trigger: 'blur' }]
				};
				return dataFormRules;
			}
		},
		methods: {
			// 获取分页数据
			findPage: function (data) {
				if (data !== null) {
					this.filters.pageNum = data
				} else {
					this.filters.pageNum = 1
					this.pageRequest.pageNum = 1
				}
				this.filters.pageSize = this.pageRequest.pageSize
				this.$api.role.findPage(this.filters).then((res) => {
					this.pageResult = res.data
					console.log(this.pageResult);
					this.findTreeData()
				}).then(data != null ? data.callback : '')
			},
			// 批量删除
			handleDelete: function (index, data) {
				let params = [{ 'id': data.id }]
				this.$api.role.batchDelete(params).then((res) => {
					this.findPage(null)
				}).then(data.callback)

			},
			// 显示新增界面
			handleAdd: function () {
				this.dialogVisible = true
				this.operation = true
				this.dataForm = {
					id: 0,
					name: '',
					remark: ''
				}
			},
			// 显示编辑界面
			handleEdit: function (params, row) {
				this.dialogVisible = true
				this.operation = false
				this.dataForm = Object.assign({}, row)
			},
			// 编辑
			submitForm: function () {
				this.$refs.dataForm.validate((valid) => {
					if (valid) {
						this.$confirm(this.getKey('action.isConfirm'), this.getKey('action.tips'), {}).then(() => {
							this.editLoading = true
							let params = Object.assign({}, this.dataForm)
							this.$api.role.save(params).then((res) => {
								this.editLoading = false
								if (res.code == 200) {
									this.$message({ message: this.getKey('action.operateSucess'), type: 'success' })
									this.dialogVisible = false
									this.$refs['dataForm'].resetFields()
								} else {
									this.$message({ message: this.getKey('action.operateFail') + res.msg, type: 'error' })
								}
								this.findPage(null)
							})
						})
					}
				})
			},
			// 获取数据
			findTreeData: function () {
				this.menuLoading = true
				this.$api.menu.findMenuTree().then((res) => {
					this.menuData = res.data
					this.menuLoading = false
				})
			},
			// 角色选择改变监听
			handleRoleSelectChange(index, val) {
				this.dialogRoleVisible = true;
				this.selectRole = val
				this.$api.role.findRoleMenus({ 'roleId': val.id }).then((res) => {
					this.currentRoleMenus = res.data
					this.$refs.menuTree.setCheckedNodes(res.data);

				})
			},
			// 树节点选择监听
			handleMenuCheckChange(data, check, subCheck) {
				if (check) {
					// 节点选中时同步选中父节点
					let parentId = data.parentId
					this.$refs.menuTree.setChecked(parentId, true, false)
					// debugger
					// data.children.forEach(menu => {				
					// 	if(data.parentId===menu.id) {
					// 		this.$refs.menuTree.setChecked(menu.id, true, false)
					// 	}
					// });
				} else {
					// 节点取消选中时同步取消选中子节点
					if (data.children != null) {
						data.children.forEach(element => {
							this.$refs.menuTree.setChecked(element.id, false, false)
						});
					}
				}
			},
			// 重置选择
			resetSelection() {
				this.checkAll = false
				this.$refs.menuTree.setCheckedNodes(this.currentRoleMenus)
			},
			// 全选操作
			handleCheckAll() {
				if (this.checkAll) {
					let allMenus = []
					this.checkAllMenu(this.menuData, allMenus)
					this.$refs.menuTree.setCheckedNodes(allMenus)
				} else {
					this.$refs.menuTree.setCheckedNodes([])
				}
			},
			// 递归全选
			checkAllMenu(menuData, allMenus) {
				menuData.forEach(menu => {
					allMenus.push(menu)
					if (menu.children) {
						this.checkAllMenu(menu.children, allMenus)
					}
				});
			},
			// 角色菜单授权提交
			submitAuthForm() {
				let roleId = this.selectRole.id
				// if('admin' == this.selectRole.name) {
				// 	this.$message({message: '超级管理员拥有所有菜单权限，不允许修改！', type: 'error'})
				// 	return
				// }
				this.authLoading = true
				let checkedNodes = this.$refs.menuTree.getCheckedNodes(false, true)
				let roleMenus = []
				for (let i = 0, len = checkedNodes.length; i < len; i++) {
					let roleMenu = { roleId: roleId, menuId: checkedNodes[i].id }
					roleMenus.push(roleMenu)
				}
				this.$api.role.saveRoleMenus(roleMenus).then((res) => {
					if (res.code == 200) {
						this.$message({ message: this.getKey('action.operateSucess'), type: 'success' })
					} else {
						this.$message({ message: this.getKey('action.operateFail') + res.msg, type: 'error' })
					}
					this.authLoading = false;
					this.dialogRoleVisible = false;
				})
			},
			renderContent(h, { node, data, store }) {
				return (
					<div class="column-container">
						<span style="text-algin:center;margin-right:80px;">{data.name}</span>
						<span style="text-algin:center;margin-right:80px;">
							<el-tag type={data.type === 0 ? '' : data.type === 1 ? 'success' : 'info'}   size="global.gSize">
								{data.type === 0 ? this.getKey('common.catalog') : data.type === 1 ? this.getKey('common.menu') : this.getKey('common.button')}
							</el-tag>
						</span>
						<span style="text-algin:center;margin-right:80px;"> <i class={data.icon}></i></span>
						<span style="text-algin:center;margin-right:80px;">{data.parentName ? data.parentName : this.getKey('common.parentMenu')}</span>
						<span style="text-algin:center;margin-right:80px;">{data.url ? data.url : '\t'}</span>
					</div>);
			},
			// 时间格式化
			dateFormat: function (row, column, cellValue, index) {
				return format(row[column.property])
			},
			getKey: function (arg) {
				return this.$t(arg)
			}

		},
		mounted() {
			this.findPage(null)
		},
		watch: {

			dialogVisible(to, from) {
				if (this.$refs['dataForm'] !== undefined) {
					this.$refs["dataForm"].resetFields();
				}
			}
		}
	}
</script>
<style scoped>
	.menu-container {
		margin-top: 10px;
	}

	.menu-header {
		padding-left: 8px;
		padding-bottom: 5px;
		text-align: left;
		font-size: 16px;
		color: rgb(20, 89, 121);

	}
</style>